package cn.tuning.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.IOException;
import java.util.Properties;
import java.util.UUID;


/**
 * @author lixiaolong
 * @date 2021-08-03 21:56
 * @description: 邮件发送工具类
 */
@Component
public class MailUtil {

    @Autowired
    JavaMailSender javaMailSender;//在spring中配置的邮件发送的bean


    public String sentEmail(String receiverEmail) {
        MimeMessage mMessage = javaMailSender.createMimeMessage();//创建邮件对象
        MimeMessageHelper mMessageHelper;
        Properties prop = new Properties();
        String from;
        String verificationCode = null; //验证码
        try {
            //从配置文件中拿到发件人邮箱地址
            prop.load(this.getClass().getResourceAsStream("/mailconfig.properties"));
            from = prop.get("mail.smtp.username") + "";
            mMessageHelper = new MimeMessageHelper(mMessage, true);
            mMessageHelper.setFrom(from);//发件人邮箱
            mMessageHelper.setTo(receiverEmail);//收件人邮箱
            mMessageHelper.setSubject("Science and Technology Ltd");//邮件的主题
            verificationCode = UUID.randomUUID().toString().substring(0, 4);//验证码生成
            mMessageHelper.setText("<p>你好,你的验证码是</p></br>" + verificationCode, true);//邮件的文本内容，true表示文本以html格式打开
            javaMailSender.send(mMessage);//发送邮件
        } catch (MessagingException | IOException e) {
            e.printStackTrace();
        }
        return verificationCode;//返回验证码
    }

}
